package br.com.passeionaweb.appengine.tabelafipe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.passeionaweb.appengine.tabelafipe.data.DataProvider;
import br.com.passeionaweb.appengine.tabelafipe.data.Make;
import br.com.passeionaweb.appengine.tabelafipe.data.Model;
import br.com.passeionaweb.appengine.tabelafipe.data.PMF;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class UpdateModelsServlet extends HttpServlet {

	private static final PersistenceManager pm = PMF.get().getPersistenceManager();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		long start = Calendar.getInstance().getTimeInMillis();
		boolean result = updateModels();
		long end = Calendar.getInstance().getTimeInMillis();
		resp.getWriter().write("{result:"+result+",time:"+((end - start) / 1000)+"}");

	}

	@SuppressWarnings("unchecked")
	private boolean updateModels() {
		pm.deletePersistentAll((List<Model>)pm.newQuery(Model.class).execute());
		try {
			JSONArray jsonModels = new JSONArray(DataProvider.getModelsJSON());
			ArrayList<Model> models = new ArrayList<Model>();
			for (int i = 0; i < jsonModels.length(); ++i) {
				JSONObject jsonmodel = jsonModels.getJSONObject(i);
				String makeName = jsonmodel.getString(Make.KEY_MAKE);
				String modelName = jsonmodel.getString(Model.KEY_MODEL);
				Make make;

				if (Make.exists(makeName)) {
					make = Make.getMake(makeName);
				} else {
					make = new Make(makeName);
					pm.makePersistent(make);
					make = Make.getMake(make.getMake());
				}
				if (!Model.exists(modelName)) {
					models.add(new Model(modelName, make.getId()));
				}
				logPercentage(i, jsonModels.length());
			}

			if (!models.isEmpty()) {
				pm.makePersistentAll(models);
			}

			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	private void logPercentage(int done, int size) {
		float percentage = Float.valueOf(done) / Float.valueOf(size) * 100;
		System.out.println("Updating MODELS: " + percentage + "%");
	}
}
